﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.FindSymbols;
using Roslyn.Utilities;

namespace RoslynTest.Analyzers.Lib
{
    class SequenceAnalyzer
    {
        private Solution _solution;
        private readonly MSBuildWorkspace _workspace;

        public SequenceAnalyzer(string solutionPath)
        {
            _workspace = MSBuildWorkspace.Create();
            _solution = _workspace.OpenSolutionAsync(solutionPath).Result;

            RemoveTestProjects();
        }

        public async Task<IEnumerable<NodeWithChildren<MethodDeclarationSyntax>>> FindMethodCallingSequence(MethodLocator methodLocator)
        {
            var document = GetDocument(methodLocator.FilePath);
            var token = await GetToken(document, methodLocator);

            return await AnalyzeToken(document, token);
        }

        private async Task<IEnumerable<NodeWithChildren<MethodDeclarationSyntax>>> AnalyzeToken(Document document, SyntaxToken token)
        {
            var method = FindContainingMethod(token);
            if (method == null)
                throw new Exception("Token is not a method.");

            return await Task.Factory.StartNew(() => BuildGraph(method, GetMethodReferences, new MethodComparer()));
        }

        private IEnumerable<MethodDeclarationSyntax> GetMethodReferences(MethodDeclarationSyntax method)
        {
            var document = GetDocument(method.Identifier.SyntaxTree.FilePath);
            var symbol = SymbolFinder.FindSymbolAtPosition(document.GetSemanticModelAsync().Result, method.Identifier.SpanStart, _workspace);
            var references = SymbolFinder.FindReferencesAsync(symbol, _solution).Result;

            var methodComparer = new MethodComparer();
            foreach (var reference in references)
            {
                foreach (var location in reference.Locations)
                {
                    var callingMethod = FindContainingMethod(location);
                    if (callingMethod == null || methodComparer.Equals(callingMethod, method)) continue;

                    yield return callingMethod;
                }
            }
        }

        private MethodDeclarationSyntax FindContainingMethod(ReferenceLocation location)
        {
            var position = location.Location.SourceSpan.Start;
            var root = location.Location.SourceTree.GetRootAsync().Result;
            var syntaxNode = root.FindToken(position).Parent;

            return syntaxNode.FirstAncestorOrSelf<MethodDeclarationSyntax>() ?? default(MethodDeclarationSyntax);
        }

        private MethodDeclarationSyntax FindContainingMethod(SyntaxToken token)
        {
            return token.Parent as MethodDeclarationSyntax ?? default(MethodDeclarationSyntax);
        }

        private Document GetDocument(string filePath)
        {
            var document = (from p in _solution.Projects
                    from d in p.Documents
                    where d.FilePath == filePath
                    select d).FirstOrDefault();

            if (document == null)
                throw new Exception("Can't find matching file.");

            return document;
        }

        /// <summary>
        /// This is so lame...
        /// </summary>
        private void RemoveTestProjects()
        {
            List<ProjectId> toDelete = new List<ProjectId>();

            foreach (var p in _solution.Projects)
            {
                if (p.AssemblyName == "RoslynTest.Analyzers")
                    continue;

                if (p.Name.Contains("Stub"))
                {
                    toDelete.Add(p.Id);
                    continue;
                }

                foreach (var d in p.Documents)
                {
                    if (d.GetTextAsync().Result.ToString().Contains("[TestClass]"))
                    {
                        toDelete.Add(p.Id);
                        break;
                    }
                }
            }

            foreach (var toDeleteId in toDelete)
            {
                _solution = _solution.RemoveProject(toDeleteId);
            }
        }

        private IEnumerable<NodeWithChildren<T>> BuildGraph<T>(T root, Func<T, IEnumerable<T>> children, IEqualityComparer<T> comparer)
        {
            var seen = new HashSet<T>();
            var stack = new Stack<Tuple<T, int>>();
            stack.Push(new Tuple<T, int>(root, 0));
            
            while (stack.Count != 0)
            {
                var item = stack.Pop();

                if (seen.Contains(item.Item1, comparer))
                {
                    continue;
                }
                seen.Add(item.Item1);
                var itemChildren = children(item.Item1);

                yield return new NodeWithChildren<T> { Node = item.Item1, Children = itemChildren, Depth = item.Item2 };
                foreach (var child in itemChildren)
                {
                    stack.Push(new Tuple<T, int>(child, item.Item2 + 1));
                }
            }
        }

        private async Task<SyntaxToken> GetToken(Document document, MethodLocator methodLocator)
        {
            var root = await document.GetSyntaxRootAsync();
            var methods =
                root.DescendantNodes()
                    .OfType<MethodDeclarationSyntax>()
                    .Where(
                        m =>
                        m.Identifier.ValueText == methodLocator.MethodName &&
                        m.ParameterList.Parameters.Count == methodLocator.MethodParametersNumber)
                    .ToList();
            if (!methods.Any())
                throw new Exception("Can't find matching method.");

            return root.FindToken(methods.First().Identifier.SpanStart);
        }
    }
}
